package cn.zktr.Personnel.model.service.tantiantian;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.zktr.Personnel.common.TimeStamp;
import cn.zktr.Personnel.controllers.zhouyongcong.end.separationController;
import cn.zktr.Personnel.model.dao.tantiantian.SlySetDao;
import cn.zktr.Personnel.model.dao.tantiantian.SlySlDao;
import cn.zktr.Personnel.model.dao.tantiantian.SlySzDao;
import cn.zktr.Personnel.model.dao.tantiantian.SlyWagDao;
import cn.zktr.Personnel.model.mappers.tantiantian.PaymentMapper;
import cn.zktr.Personnel.model.mappers.tantiantian.PmsStmMapper;
import cn.zktr.Personnel.model.mappers.tantiantian.ScsyMapper;
import cn.zktr.Personnel.model.mappers.tantiantian.SlMapper;
import cn.zktr.Personnel.model.mappers.tantiantian.SlySetMapper;
import cn.zktr.Personnel.model.pojos.PerPmsDis;
import cn.zktr.Personnel.model.pojos.PerSlySet;
import cn.zktr.Personnel.model.pojos.PerSlySls;
import cn.zktr.Personnel.model.pojos.PerSlySz;
import cn.zktr.Personnel.model.pojos.PerSlyWags;
import cn.zktr.Personnel.model.service.zhouxiong.KaoQinKaService;
import cn.zktr.Personnel.model.service.zhouxiong.NoimpService;
import cn.zktr.Personnel.model.service.zhouxiong.QiTaYeWuService;
import cn.zktr.Personnel.model.service.zhouyongcong.findService;
import cn.zktr.Personnel.model.service.zhouyongcong.saveAuditService;
import cn.zktr.Personnel.model.service.zhouyongcong.saveService;
import cn.zktr.Personnel.model.service.zhouyongcong.end.separationService;
import cn.zktr.Personnel.model.service.zhouyongcong.monit.monitObj;
import cn.zktr.Personnel.model.service.zhouyongcong.monit.monitgetService;
import cn.zktr.Personnel.model.service.zhouyongcong.monit.monitsaveService;
import cn.zktr.Personnel.model.uitls.Homapape;
/**
 * @author lenovo
 *
 */
@Service
@Transactional(rollbackOn=Exception.class)
public class SlySlService {
	@Autowired
	private saveAuditService sas;
	
	@Autowired
	private monitsaveService mss; 
	/**
	 * 薪资单dao
	 */
	@Autowired
	private SlySlDao slDao;
	@Autowired
	private SlMapper slmer;
	
	/**
	 * 社保套账  
	 */
	@Autowired
	private SlySzDao szDao;
	@Autowired
	private	ScsyMapper scsyMer;
	
	/**
	 * 套账表--员工表（中间表）
	 * 薪资发放
	 */
	@Autowired
	private PaymentMapper paymer;
	/**
	 * 薪资套账dao
	 */
	@Autowired
	private SlySetDao setDao;
	@Autowired 
	private SlySetMapper setmer;
	
	/**
	 * 员工
	 */
	@Autowired
	private PmsStmMapper stmmer;
	
	/**
	 * 员工工资单
	 */
	@Autowired
	private SlyWagDao wagDao;
	/**
	 * 考勤
	 */
	@Autowired
	private QiTaYeWuService qingjias;
	@Autowired
	private KaoQinKaService kaoqin;
	@Autowired
	private NoimpService jiabans;
	
	@Autowired
	private QiTaYeWuService tian;
	
	/**
	 * 员工
	 */
	@Autowired
	private findService findser;
	/**
	 * @return查询所有薪资发放
	 */
	public JSONArray seleSlAll() {
		return slmer.seleSlAll();
	}
	
	/**
	 * @return查询所有社保套账
	 */
	public JSONArray seleSz(){
		return slmer.sele_shebao();
		
	}
	/**
	 * @param setid
	 * @return根据套帐id查询套帐-员工表（中间表）下的所有员工
	 */
	public JSONArray seleceAll(Integer setid) {
		return paymer.seleceAll(setid);
	}
	/**
	 * @param ids
	 * @return根据社保套账id查询
	 */
	public Optional<PerSlySz> seleSzId(Integer ids){
		return szDao.findById(ids);
	}
	
	/**
	 * @param ids
	 * @return 根据薪资套账id查询 
	 */
	public Optional<PerSlySet> seleSetId(Integer ids){
		return setDao.findById(ids);
	}
	
	/**
	 * @param pjtname
	 * @param setid
	 * @return根据套账和项目名称查询项目值
	 */
	public JSONArray seleTX(String pjtname,Integer setid) {
		return paymer.seleTX(pjtname, setid);
		
	}
	/**
	 * @param pjtname
	 * @param setid
	 * @return根据套账和项目名称查询项目值
	 */
	 public JSONArray seleSlBy_(String pjtname) {
			return slmer.seleSlBy_("%"+pjtname+"%");	
	 }
	 /**
		 * @param sls
		 * @return新增单（薪资发放）
		 */
		@SuppressWarnings("deprecation")
		public void addSls(PerSlySls sls,Integer perSlySets,Integer perPmsEmp2,HttpSession session) {
					//日期
			Timestamp time = new TimeStamp().getNetworkTime();
					sls.setSlstime(1900+time.getYear()+"-"+time.getMonth());
					//状态
					sls.setSlsstat(0);
					//创建人
					sls.setPerPmsEmp1(findser.findEmpid(Integer.valueOf(session.getAttribute("id")+"")));
					//审批人
					sls.setPerPmsEmp2(stmmer.seleEmpids(perPmsEmp2));
					//薪资套账
					//slser.seleSzId(perSlySzs);
					sls.setPerSlySet(setDao.findById(perSlySets).get());
					slDao.save(sls);
		}
	/**
	 * @param empid
	 * @param perSlySzs新增工资单--员工工资单
	 */
		@Autowired
		private separationService sq;
	public void addWagEmp(String[] empid,Integer perSlySzs,Integer perSlySets,HttpSession session) {
		//查询最新添加的薪资单
		PerSlySls sls=paymer.seleSlsLimit();
		//根据社保id查询社保对象
		 PerSlySz sz = szDao.findById(perSlySzs).get();
		 //根据套帐id查询该套帐下所有薪资项目
		 JSONArray tsx_pjt = paymer.seletsx_setis(perSlySets);
		 //总金额
		 //循环员工
		for(int i=0;i<empid.length-1;i++) {
			System.err.println(empid[i]);
				//实发
				Double Totalsum=0.0;
				//请假
				Double qingjia=0.0;
				//应发
				Double yingfa=0.0;
				//迟到
				Double chidao=0.0;
				//加班
				Double jiabany=0.0;
				//外勤
				Double waiqin=0.0;
				//早退
				Double zaotui=0.0;
				//社保
				Double shebao=0.0;
				//全勤
				Double quanqin=0.0;
				//旷工
				Double kuanggong=0.0;
				//拿到固定值
				JSONArray PjtGuDing = slmer.selePjtGuDing(perSlySets);
				for (int s=0;s<PjtGuDing.size();s++) {
					JSONObject obj=PjtGuDing.getJSONObject(s);
					//转成jsonObject
					if(obj.get("PJTNAME").equals("全勤")) {
						quanqin=Double.parseDouble(obj.get("TSXVAL").toString());
					}else {
						Totalsum+=Double.parseDouble(obj.get("TSXVAL").toString());
					}
					
				}
				Timestamp time = new TimeStamp().getNetworkTime();	
				String da="";
				if(time.getMonth()<10) {
					da="0"+time.getMonth();
				}//打卡天数
				System.err.println(1900+time.getYear()+"-"+time.getMonth()+"日期");
				JSONObject selectTongJi = tian.selectTongJi(Integer.parseInt(empid[i]),1900+time.getYear()+"-"+da);
 				if(selectTongJi!=null) {
						System.err.println("打卡次数"+selectTongJi.get("qdcs"));
					    if(Integer.parseInt(selectTongJi.get("qdcs")+"")<22&&Integer.parseInt(selectTongJi.get("qdcs")+"")>19) {
							quanqin=0.0;
							JSONArray kuang = slmer.seleSlBy_pjtname(perSlySets,"旷工");
							if(kuang.size()>0) {
								JSONObject chidaoobjs=kuang.getJSONObject(0);
								kuanggong=(22-Integer.parseInt(selectTongJi.get("qdcs")+""))*Double.parseDouble(chidaoobjs.get("TSXVAL").toString());
							}
						}else if(Integer.parseInt(selectTongJi.get("qdcs")+"")==0||Integer.parseInt(selectTongJi.get("qdcs")+"")<=19){
						quanqin=0.0;
						//实发
						 Totalsum=0.0;
						//请假
						 qingjia=0.0;
						//应发
						 yingfa=0.0;
						//迟到
						 chidao=0.0;
						//加班
						 jiabany=0.0;
						//外勤
						 waiqin=0.0;
						//早退
						 zaotui=0.0;
						//社保
						 shebao=0.0;
						 System.err.println(empid[i]+"员工编号");
						sq.adddis(Integer.parseInt(empid[i]),findser.findEmpid(Integer.valueOf(session.getAttribute("id")+"")).getEmpname()+"旷工次数大于3次/等于3次，薪资部发起该员工离职申请",true);
						System.err.println("无打卡次数");
					}
					}else {
						quanqin=0.0;
						//实发
						 Totalsum=0.0;
						//请假
						 qingjia=0.0;
						//应发
						 yingfa=0.0;
						//迟到
						 chidao=0.0;
						//加班
						 jiabany=0.0;
						//外勤
						 waiqin=0.0;
						//早退
						 zaotui=0.0;
						//社保
						 shebao=0.0;
						System.err.println(empid[i]+"员工编号");
						sq.adddis(Integer.parseInt(empid[i]),findser.findEmpid(Integer.valueOf(session.getAttribute("id")+"")).getEmpname()+"没有打卡次数，薪资部发起改员工离职申请",true);
						System.err.println("无打卡次数");
					}
				
				//把所有固定值拿到
				yingfa=Totalsum;
				JSONArray qing = qingjias.seleQinJiaQBEmp(Integer.parseInt(empid[i]));	
				if(qing.size()>0) {
					quanqin=0.0;
					//拿到请假数据
					
						for (int q=0;q<qing.size();q++) {
							JSONObject qingjiaObj=qing.getJSONObject(q);
							JSONArray seleTX = slmer.seleSlBy_pjtname(perSlySets, qingjiaObj.get("TYPEXZ").toString());
							System.err.println("shuxing+"+qingjiaObj.get("TYPEXZ").toString());
							if(seleTX.size()>0) {
								JSONObject objs=seleTX.getJSONObject(q);
								if(objs.get("PJTNAME").toString().equals("个人假")) {
									qingjia=(Double.parseDouble(objs.get("TSXVAL").toString())*Double.parseDouble(qingjiaObj.get("LAETIME").toString())/60);
									System.err.println("请假："+qingjia);
									Totalsum=Totalsum-qingjia;
									
								}
							}else {
								System.err.println("无请假");
							}
						}
				}
				//计算迟到早退
				int chinum=0;  
				int zaonum=0;
				List<JSONObject> chidaos = kaoqin.seleYuanGongKaoQin(Integer.parseInt(empid[i]),(1900+time.getYear())+"-"+da);
				if(chidaos!=null) {
					quanqin=0.0;
					for (JSONObject jsonObject : chidaos) {
						String str=jsonObject.get("CWAJG")+"";
						System.err.println(str);
						String chi=str.substring(1, 3);
						String zao=str.substring(5, 7);
						if(chi.equals("迟到")) {
							chinum++;
						}
						if(zao.equals("早退")) {
							zaonum++;
						}
						
					}
					//计算迟到
					JSONArray chidaoarr = slmer.seleSlBy_pjtname(perSlySets,"迟到");
						
						if(chidaoarr.size()>0) {
							JSONObject chidaoobjs=chidaoarr.getJSONObject(0);
							chidao=chinum*Double.parseDouble(chidaoobjs.get("TSXVAL").toString());
						}
					System.err.println("迟到次数："+chinum);
					System.err.println("早退次数："+zaotui);
					//早退
					JSONArray zaotuiarr = slmer.seleSlBy_pjtname(perSlySets,"早退");
						
						if(zaotuiarr.size()>0) {
							JSONObject zaotuiobjs=zaotuiarr.getJSONObject(0);
							zaotui=zaonum*Double.parseDouble(zaotuiobjs.get("PJTIDMRZ").toString());
						}
						Totalsum=(Totalsum-(chidao+zaotui));
				
					
				}else {
					System.err.println("无记录");
				}
				
				//计算加班
				
				List<JSONObject> Jiaban = jiabans.seleJiaBanShuJuEmpid(Integer.parseInt(empid[i]),1900+time.getYear()+"-"+da);
				System.err.println("加班日期"+da);
				System.err.println(empid[i]);
				if(Jiaban!=null) {
					for (JSONObject jsono : Jiaban) {
						System.err.println(jsono.get("RSNREASON"));
						JSONArray seleSlBy_pjtname = slmer.seleSlBy_pjtname(perSlySets,jsono.get("RSNREASON")+"");
						JSONObject jiabjson=seleSlBy_pjtname.getJSONObject(0);
						jiabany+=Double.parseDouble(jsono.get("RESTIME").toString())/60*Double.parseDouble(jiabjson.get("TSXVAL").toString());
					}
					Totalsum=Totalsum+jiabany;
				}else{
					System.err.println("无加班");
				}
				
				//计算社保
				JSONArray sztax = scsyMer.selecSzTax(perSlySzs);
				if(sztax.size()>0){
					for(int i1=0;i1<sztax.size();i1++) {
						System.err.println("进来了");
						JSONObject sztaxs=sztax.getJSONObject(i1);
						//社保大于固定值小于最大值
						if(Totalsum>=Double.parseDouble(sztaxs.get("TAXMIN")+"")&&Totalsum<=Double.parseDouble(sztaxs.get("TAXMAX")+"")) {
							shebao+=Totalsum*Double.parseDouble(sztaxs.get("TAXGR")+"");
						//	System.err.println("社保1:"+shebao); 
						//社保小于最小值
						}else if(Totalsum<=Double.parseDouble(sztaxs.get("TAXMIN")+"")) {
							System.err.println("无");
						//社保大于最大值
						}else if(Totalsum>=Double.parseDouble(sztaxs.get("TAXMAX")+"")) {
						//	System.err.println("社保2:"+shebao);
							shebao+=Double.parseDouble(sztaxs.get("TAXMAX")+"")*Double.parseDouble(sztaxs.get("TAXGR")+"");

						}
						
					}
				}else{
					System.err.println("无社保");
				}
				
				Totalsum=Totalsum-shebao;
				//全勤
				Totalsum+=quanqin;
				//旷工
				Totalsum=Totalsum-kuanggong;
				if(Totalsum<0) {
					Totalsum=0.0;
				}
				//保留小数测试
				qingjia = (double)Math.round(qingjia*100)/100;
				shebao = (double)Math.round(shebao*100)/100;
				jiabany = (double)Math.round(jiabany*100)/100;
				PerSlyWags wg=new PerSlyWags();
				if(sz.getSzname()!="") {
					wg.setPerSlySz(sz);
				}else if(sz.getSzname()=="") {
					wg.setPerSlySz(null);
				}
				wg.setPerSlySl(sls);
				//员工
				wg.setPerPmsEmp(stmmer.seleEmpids(Integer.parseInt(empid[i])));
				//请假
				wg.setWagsqj(qingjia+"");
				//迟到
				wg.setWagscd(chidao+"");
				//早退
				wg.setWagszt(zaotui+"");
				//加班
				wg.setWagsjb(jiabany+"");
				//旷工
				wg.setWagswq(kuanggong+"");
				//社保
				wg.setWagssb(shebao+"");
				//实发
				wg.setWagssf(Totalsum+"");
				//应发
				wg.setWagsyf(yingfa+"");
				System.err.println("haha"+sz);
				wagDao.save(wg);
				//查找离职表是否有信息
				List<PerPmsDis> dis = stmmer.seleEmpdis(Integer.parseInt(empid[i]));
				if(dis.size()>0){
					stmmer.deletYxzs(Integer.parseInt(empid[i]));
				}else {
					System.err.println("无离职人员");
				}
		
		}
		
	} 

	public List<JSONObject> seleByslsId(Integer id) {
		//根据id查询薪资单
		 JSONArray sls = slmer.seleSlsById(id);
		 JSONObject slsobj=sls.getJSONObject(0);
		//查询所有固定值
		 JSONArray guding = slmer.selePjtGuDing(Integer.parseInt(slsobj.get("SETID")+""));
		 //查询该薪资单下所有员工
		 JSONArray yuangong = slmer.seleSlsYuanGongById(id);
		List<JSONObject> map=new ArrayList<>();
		
		 for(int i=0;i<yuangong.size();i++) {
			 JSONObject gudingObj = new JSONObject();
			 JSONObject yuangongObj=yuangong.getJSONObject(i);
			 gudingObj.put("员工姓名", yuangongObj.get("EMPNAME"));
			 gudingObj.put("请假",  "-"+yuangongObj.get("WAGSQJ"));
			 gudingObj.put("加班", "+"+yuangongObj.get("WAGSJB"));
			 gudingObj.put("迟到(50/次)","-"+yuangongObj.get("WAGSCD"));
			 gudingObj.put("早退(50/次)","-"+yuangongObj.get("WAGSZT"));
			 gudingObj.put("旷工(200/次)","-"+yuangongObj.get("WAGSWQ"));
			 gudingObj.put("社保","-"+yuangongObj.get("WAGSSB"));
			 gudingObj.put("应发工资", yuangongObj.get("WAGSYF"));
			 gudingObj.put("实发工资", yuangongObj.get("WAGSSF"));
			
			 for(int n=0;n<guding.size();n++) {
				 JSONObject gudingObjs=guding.getJSONObject(n);
				 if(yuangongObj.get("WAGSYF").toString().equals("0.0")&&yuangongObj.get("WAGSSF").toString().equals("0.0")) {
					 System.err.println("没工资"+gudingObjs.get("PJTNAME"));
					 gudingObj.put(gudingObjs.get("PJTNAME")+"","+0.0");
			
				 }else if(!yuangongObj.get("WAGSYF").toString().equals("0.0")){
					 if(gudingObjs.get("PJTNAME").equals("全勤")) {
						 //无请假，旷工，迟到，早提，有全勤
						 if(yuangongObj.get("WAGSQJ").equals("0.0")&&yuangongObj.get("WAGSCD").equals("0.0")&&yuangongObj.get("WAGSZT").equals("0.0")&&yuangongObj.get("WAGSWQ").equals("0.0")) {
							 gudingObj.put(gudingObjs.get("PJTNAME")+"","+"+gudingObjs.get("TSXVAL"));
						 }else {
							 //有请假，旷工，迟到，早提，无全勤
							 gudingObj.put(gudingObjs.get("PJTNAME")+"","+0.0");
						 }
					 }else{
						 gudingObj.put(gudingObjs.get("PJTNAME")+"","+"+gudingObjs.get("TSXVAL"));
					 }
				 }
				 
				 
			 }
                /*for (Map.Entry<String, Object> entry : gudingObj.entrySet()) {
		            System.out.println(entry.getKey() + ":" + entry.getValue());
		        }*/
			 map.add(gudingObj);
		 }
		 
		return map;
		
	}
//薪资发放送审
	@Autowired
	private monitgetService mgs;
	@Autowired
	private findService fs;
	@Autowired
	private saveService ss;
	public monitObj setmo1(Integer slsid) {
		PerSlySls sls = slDao.findById(slsid).get();
		mgs.getPojos(sls);
		monitObj mo1 = new monitObj(false,false);
		sls.setSlsstat(1);
		slDao.save(sls);
		mo1.setOld_obj(sls);
		
		PerSlySls sls1 = new PerSlySls();
		sls1.setSlsstat(2);
		mo1.setNew_obj(sls1); 
		
		return mo1;
	}
	public void Account_fafang_songshen(Integer slsid) {
		PerSlySls sls = slDao.findById(slsid).get();
		monitObj[] mos = {setmo1(slsid)};
		//1.审核类型
		//2.审核发起人
		//3.审核标题
		//4.审核的文本
		ss.save_Audit_id(6,sls.getPerPmsEmp1().getEmpid(),"薪资发放审核", fs.findEmpid(sls.getPerPmsEmp1().getEmpid()).getEmpname()+"发起薪资发放审核，请审核！");
		mss.save(sls.getPerPmsEmp1().getEmpid(), mos, 6);
		
	}
//查看个人薪资
	public JSONArray sele_mysal(HttpSession session) {
		//System.err.println(Integer.valueOf(session.getAttribute("id")+""));
		System.err.println("我的新资质登录人"+Integer.valueOf(session.getAttribute("id")+""));
		return slmer.sele_mysal(Integer.valueOf(session.getAttribute("id")+""));
	}
	//查看所有薪资
	public JSONArray sele_xinzichaxun(){
		return slmer.sele_xinzichaxun();
	}
	public void fafang(Integer slsid) throws HttpException, IOException {
		//薪资单状态修改
		PerSlySls perSlySls = slDao.findById(slsid).get();
		perSlySls.setSlsstat(3);
		JSONArray sele_wag_slsid = slmer.sele_wag_slsid(slsid);
		 JSONArray sele_phoe = slmer.sele_phoe(slsid);
		 System.err.println("发放薪资"+sele_wag_slsid.size());
		 for (int i = 0; i <sele_wag_slsid.size(); i++) {
			JSONObject ob=(JSONObject) sele_phoe.get(i);
			JSONObject ob1=(JSONObject)sele_wag_slsid.get(i);
			PerSlyWags W = wagDao.findById((Integer) ob1.get("WAGSID")).get();
			W.setWagsstat(1);
//			System.err.println(ob);
//			System.err.println("电话号码"+ob.get("lxphone")+"编号"+ob.get("lxfsid"));
			wagDao.save(W);
		//	System.err.println(ob.get("lxphone"));
			HttpClient client = new HttpClient();
		        PostMethod post = new PostMethod("http://gbk.sms.webchinese.cn"); 
		        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
		        NameValuePair[] data ={ 
			    new NameValuePair("Uid","tiantians"),
			    new NameValuePair("Key","d41d8cd98f00b204e980"),
			    new NameValuePair("smsMob",ob.get("lxphone")+""),
			    new NameValuePair("smsText",ob.get("empname")+"您好!您本月实发工资为"+ob.get("wagssf")+"元，1-3个工作日将打到您的账户上，请注意查收。【AWSLNB公司】")
		        };
		        post.setRequestBody(data);
		        client.executeMethod(post);
		        Header[] headers = post.getResponseHeaders();
		        int statusCode = post.getStatusCode();
		        System.err.println("statusCode:"+statusCode);
		        for(Header h : headers){
		           System.err.println(h.toString());
		        }
		        String result = new String(post.getResponseBodyAsString().getBytes("gbk")); 
		        System.err.println(result);	
		        post.releaseConnection();

		 }
		

	}

	public JSONArray pay_chakanshebao(Integer slsid) {
		// TODO Auto-generated method stubz[
		
		return slmer.pay_chakanshebao(slsid); 
	}
	
	public JSONArray pay_chakan(Integer sid){ 
		 return slmer.seleSlsYuanGongById(sid);
	}

	/**
	 * @param empid
	 * @return根绝员工查询工资
	 */
	public JSONArray sele_sele_mysals(Integer empid) {
		return slmer.sele_mysal(empid);
		
	}

	public void jinyong(Integer slsid) {
		PerSlySls sls = slDao.findById(slsid).get();
		sls.setSlsstat(-1);
		slDao.save(sls);
	}
}
